﻿/* Copyright (c) 2010 EPiServer AB
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Globalization;
using System.Text;
using EPiServer.Web;

namespace EPiServer.Municipality {
    public class Global : EPiServer.Global {
        /* *******************************************************************
         *  Event methods 
         * *******************************************************************/
        #region protected void Application_Start(object sender, EventArgs e)
        /// <summary>
        /// This method is called when the Application's Start event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
        protected void Application_Start(object sender, EventArgs e) {
            UrlSegment.CreatedUrlSegment += UrlSegment_CreatedUrlSegment;
        }
        #endregion
        #region static void UrlSegment_CreatedUrlSegment(object sender, UrlSegmentEventArgs e)
        /// <summary>
        /// This method is called when the UrlSegment's CreatedUrlSegment event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="UrlSegmentEventArgs"/> of the event.</param>
        static void UrlSegment_CreatedUrlSegment(object sender, UrlSegmentEventArgs e) {
            if (e.IsModified && !string.IsNullOrEmpty(e.PageData.URLSegment)) {
                e.PageData.URLSegment = e.PageData.URLSegment.EndsWith("1", StringComparison.OrdinalIgnoreCase) ? string.Empty : NormalizeUrlSegment(e.PageData.URLSegment);
            }
        }
        #endregion
        /* *******************************************************************
         *  Methods 
         * *******************************************************************/
        #region public static string NormalizeUrlSegment(string text)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string NormalizeUrlSegment(string text) {
            if (string.IsNullOrEmpty(text)) return string.Empty;

            var sb = new StringBuilder(text);

            sb.Replace(":", "-");
            sb.Replace("/", "-");
            sb.Replace("?", "-");
            sb.Replace("#", "-");
            sb.Replace("[", "-");
            sb.Replace("]", "-");
            sb.Replace("@", "-");
            sb.Replace(",", "-");
            sb.Replace(".", "-");
            sb.Replace("\"", "-");
            sb.Replace("&", "-");
            sb.Replace("'", "-");
            sb.Replace(" ", "-");
            sb.Replace("(", "-");
            sb.Replace(")", "-");

            RemoveDiacritics(sb);

            while (sb.ToString().IndexOf("--", StringComparison.OrdinalIgnoreCase) > -1)
                sb.Replace("--", "-");

            if (sb[0] == '-')
                sb.Remove(0, 1);

            if (sb[sb.Length - 1] == '-')
                sb.Remove(sb.Length - 1, 1);

            return sb.ToString().ToLower();
        }
        #endregion
        #region public static void RemoveDiacritics(StringBuilder input)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        public static void RemoveDiacritics(StringBuilder input) {
            var normalized = input.ToString().Normalize(NormalizationForm.FormD);
            input.Remove(0, input.Length);

            for (var i = 0; i < normalized.Length; i++) {
                var c = normalized[i];
                if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
                    input.Append(c);
            }
        }
        #endregion
    }
}